package com.ruoyi.system.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.HomeLocation;
import com.ruoyi.system.mapper.HomeLocationMapper;
import com.ruoyi.system.service.IHomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.Map;

/**
 * 回家路径规划服务实现类
 */
@Service
public class HomeServiceImpl implements IHomeService {

    @Autowired
    private HomeLocationMapper homeLocationMapper;

    // 高德地图API密钥（在application.yml中配置）
    @Value("${amap.key}")
    private String amapKey;

    /**
     * 保存或更新家位置信息（带事务）
     */
    @Override
    @Transactional
    public int saveOrUpdateHomeLocation(HomeLocation homeLocation) {
        // 设置审计字段
        if (homeLocation.getCreateBy() == null || homeLocation.getCreateBy().isEmpty()) {
            homeLocation.setCreateBy(homeLocation.getUpdateBy());
        }
        homeLocation.setCreateTime(DateUtils.getNowDate());
        homeLocation.setUpdateTime(DateUtils.getNowDate());

        // 检查是否已有记录
        HomeLocation existing = homeLocationMapper.selectHomeLocationByUserId(homeLocation.getUserId());
        if (existing != null) {
            // 存在则更新（复用原有ID）
            homeLocation.setId(existing.getId());
            return homeLocationMapper.updateHomeLocation(homeLocation);
        } else {
            // 不存在则新增
            return homeLocationMapper.insertHomeLocation(homeLocation);
        }
    }

    /**
     * 根据用户ID查询家位置
     */
    @Override
    public HomeLocation getHomeLocationByUserId(Long userId) {
        return homeLocationMapper.selectHomeLocationByUserId(userId);
    }

    /**
     * 调用高德地图API计算路径
     */
    @Override
    public Map<String, Object> calculateRoute(String startLat, String startLng, String endLat, String endLng) {
        // 构建请求参数（字符串形式，适配若依HttpUtils）
        String url = "https://restapi.amap.com/v3/direction/driving";
        StringBuilder params = new StringBuilder();
        params.append("origin=").append(startLng).append(",").append(startLat);
        params.append("&destination=").append(endLng).append(",").append(endLat);
        params.append("&key=").append(amapKey);
        params.append("&output=json");

        // 发送GET请求调用高德API
        String response = HttpUtils.sendGet(url, params.toString());

        // 封装返回结果
        Map<String, Object> result = new HashMap<>(2);
        if (response != null) {
            result.put("success", true);
            result.put("data", response);
        } else {
            result.put("success", false);
            result.put("message", "路径规划失败，请检查网络或API密钥");
        }

        return result;
    }
    @Override
    public Map<String, Object> regeo(String lat, String lng) {
        String url = "https://restapi.amap.com/v3/geocode/regeo";
        StringBuilder params = new StringBuilder();
        params.append("location=").append(lng).append(",").append(lat);
        params.append("&key=").append(amapKey);
        params.append("&output=json");

        String response = HttpUtils.sendGet(url, params.toString());

        Map<String, Object> result = new HashMap<>(2);
        if (response != null) {
            result.put("success", true);
            result.put("data", response);
        } else {
            result.put("success", false);
            result.put("message", "逆地理编码失败，请检查网络或API密钥");
        }
        return result;
    }

}